package iedcyt.acute.dataAccess.dao.maauco;

import iedcyt.acute.dataAccess.domain.maauco.Au0;
import iedcyt.acute.dataAccess.domain.maauco.Co0;
import iedcyt.acute.dataAccess.generic.SpringDao;
import iedcyt.acute.dataAccess.idao.maauco.IRPDao;
import iedcyt.acute.dataAccess.utils.Pair;

import java.util.List;



public class RPDao extends SpringDao implements IRPDao  {


	/**
	 * @see iedcyt.acute.dataAccess.idao.maauco.IAu0Dao#create()
	 */
	@Override
	public void create() {
		//comprobamos si la tabla existe y si no la creamos
		try {
			_jdbcTemplate.queryForInt("select count(*) from RPs");
		} catch (Exception e) {
			String sqlins = "CREATE TABLE RPs (IDNO numeric, NO numeric, AUTH varchar(100), CORP varchar(255), COUNTRY varchar(100), YEAR varchar(4), PROVINCIA varchar(2), INSTIT varchar(4), ORGANISMO varchar(6), DPTO varchar(8), ISO varchar(2))";
			String sqlidx = "CREATE INDEX idxRPs on RPs (idno) WITH PRIMARY DISALLOW NULL";
			_log.info(sqlins);
			_log.info(sqlidx);
			_jdbcTemplate.execute(sqlins);
			_jdbcTemplate.execute(sqlidx);
			
		}
	}
	
	/**
	 * @see iedcyt.acute.dataAccess.idao.maauco.IRPDao#insert(iedcyt.acute.dataAccess.utils.Pair)
	 */
	@Override
	public void insert(Pair<Au0, Co0> pair) {
				
		Co0 co0 = pair.getSecond();
		Au0 au0 = pair.getFirst();
				
		_jdbcTemplate.update("INSERT INTO RPs (IDNO , NO , AUTH, CORP , COUNTRY , YEAR , PROVINCIA , INSTIT , ORGANISMO, DPTO, ISO) VALUES (?,?,?,?,?,?,?,?,?,?,?)",
		new Object[] { co0.get_IDNO(), -1, au0.get_auth(), co0.get_CORP(),co0.get_COUNTRY(), co0.get_YEAR(), co0.get_PROVINCIA(), co0.get_INSTIT(),
		co0.get_ORGANISMO(), co0.get_DPTO(), co0.get_ISO()});

	}
	
	/**
	 * @see iedcyt.acute.dataAccess.idao.maauco.IRPDao#selectAll()
	 */
	@Override
	public List<Pair<Au0, Co0>> selectAll() {
		
		
		return _jdbcTemplate.query("SELECT * FROM RPs",
				new RPRowMapper());
	}
	
	

	@Override
	public List<Pair<Au0, Co0>> selectByIdnoRange(int idno1,
			int idno2) {
		return _jdbcTemplate
		.query(
				"SELECT * FROM RPs WHERE IDNO >= ? AND IDNO <= ?",
				new Object[] { idno1, idno2 },
				new RPRowMapper());
	}

	
	@Override
	public List<Pair<Au0, Co0>> select(int idno) {
		return _jdbcTemplate
		.query(
				"SELECT * FROM RPs WHERE IDNO = ?",
				new Object[] { idno },
				new RPRowMapper());
	}



	@Override
	public int selectMaxIdno() {
		return _jdbcTemplate.queryForInt("SELECT MAX(IDNO) FROM RPs");
	}

}

